package com.fileCenter.dao.impl;

import java.util.Collections;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Expression;

import com.fileCenter.dao.AuthorityDAO;
import com.fileCenter.dao.BaseDAO;
import com.fileCenter.exception.FileCenterException;
import com.fileCenter.pojo.Authority;

public class AuthorityDAOImpl extends BaseDAO implements AuthorityDAO {
	
	@Override
	public void insert(Authority authority) {
		if (authority == null) {
			throw new FileCenterException("param error!");
		}
		getHibernateTemplate().save(authority);
	}

	@SuppressWarnings("unchecked")
	@Override
	public Authority getAuthorityByModelIdAndFileId(long modelId, long fileId,
			int readStatus, int writeStatus, int shareStatus) {
		DetachedCriteria criteria = DetachedCriteria.forClass(Authority.class);
		criteria.add(Expression.eq("modelId", modelId));
		criteria.add(Expression.eq("fileId", fileId));
		if (readStatus > 0) {
			criteria.add(Expression.eq("readStatus", readStatus));
		}
		if (writeStatus > 0) {
			criteria.add(Expression.eq("writeStatus", writeStatus));
		}
		if (shareStatus > 0) {
			criteria.add(Expression.eq("shareStatus", shareStatus));
		}
		List<Authority> list = getHibernateTemplate().findByCriteria(criteria);
		return CollectionUtils.isEmpty(list) ? null : list.get(0);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Authority> getAuthoritysByModelId(long modelId, int readStatus,
			int writeStatus, int shareStatus) {
		DetachedCriteria criteria = DetachedCriteria.forClass(Authority.class);
		criteria.add(Expression.eq("modelId", modelId));
		if (readStatus > 0) {
			criteria.add(Expression.eq("readStatus", readStatus));
		}
		if (writeStatus > 0) {
			criteria.add(Expression.eq("writeStatus", writeStatus));
		}
		if (shareStatus > 0) {
			criteria.add(Expression.eq("shareStatus", shareStatus));
		}
		List<Authority> list = getHibernateTemplate().findByCriteria(criteria);
		return (List<Authority>) (CollectionUtils.isEmpty(list) ? 
				Collections.emptyList() : list);
	}

	@Override
	public void update(Authority authority) {
		if (authority == null || authority.getId() <= 0) {
			throw new FileCenterException("param error!");
		}
		getHibernateTemplate().update(authority);
	}

}
